<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>1669. 合并两个链表</title>
  </head>
  <body>
    <script>
      //     给你两个链表 list1 和 list2 ，它们包含的元素分别为 n 个和 m 个。

      // 请你将 list1 中下标从 a 到 b 的全部节点都删除，并将list2 接在被删除节点的位置。

      // 下图中蓝色边和节点展示了操作后的结果：

      // 请你返回结果链表的头指针。

      //

      // 示例 1：

      // 输入：list1 = [0,1,2,3,4,5], a = 3, b = 4, list2 = [1000000,1000001,1000002]
      // 输出：[0,1,2,1000000,1000001,1000002,5]
      // 解释：我们删除 list1 中下标为 3 和 4 的两个节点，并将 list2 接在该位置。上图中蓝色的边和节点为答案链表。
      // 示例 2：

      // 输入：list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004]
      // 输出：[0,1,1000000,1000001,1000002,1000003,1000004,6]
      // 解释：上图中蓝色的边和节点为答案链表。
      //

      // 提示：

      // 3 <= list1.length <= 104
      // 1 <= a <= b < list1.length - 1
      // 1 <= list2.length <= 104

      // 来源：力扣（LeetCode）
      // 链接：https://leetcode.cn/problems/merge-in-between-linked-lists
      // 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。

      /**
       * Definition for singly-linked list.
       * */
      function ListNode(val, next) {
        this.val = val === undefined ? 0 : val
        this.next = next === undefined ? null : next
      }

      /**
       * @param {ListNode} list1
       * @param {number} a
       * @param {number} b
       * @param {ListNode} list2
       * @return {ListNode}
       */
      var mergeInBetween = function (list1, a, b, list2) {
        let i = 0
        let list = list1
        let aNode = null
        let bNode = null
        let endNode = null
        while (list) {
          if (i + 1 === a) {
            aNode = list
          }
          if (i === b) {
            bNode = list.next
          }
          list = list.next
          i++
        }
        debugger
        aNode.next = list2
        while (list2) {
          list2 = list2.next
          if (list2.next === null) {
            endNode = list2
            break
          }
        }
        endNode.next = bNode
        return list1
      }

      const head = new ListNode(1)
      const sec = new ListNode(4)
      const a = new ListNode(3)
      const b = new ListNode(2)
      const c = new ListNode(5)
      const d = new ListNode(2)
      head.next = sec
      sec.next = a
      a.next = b
      b.next = c
      c.next = d

      const head1 = new ListNode(1)
      const sec1 = new ListNode(4)
      const a1 = new ListNode(3)
      const b1 = new ListNode(2)
      const c1 = new ListNode(5)
      const d1 = new ListNode(2)
      head1.next = sec1
      sec1.next = a1
      a1.next = b1
      b1.next = c1
      c1.next = d1
      console.log(mergeInBetween(head, 1, 3, head1))
    </script>
  </body>
</html>
